package com.doa;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Collection;

import thewebsemantic.Bean2RDF;
import thewebsemantic.RDF2Bean;

import com.doa.beans.Person;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;

public class DoaPerson implements Doa {

	private String file = "Data.rdf";
	private Person personBean;
	private static DoaPerson doaPerson;
	private String path;
	
	public synchronized String getPath() {
		return path;
	}

	public synchronized void setPath(String path) {
		this.path = path;
	}

	private static Model model;

	static {
		model = ModelFactory.createOntologyModel();
	}
	
	private DoaPerson() {
		// TODO Auto-generated constructor stub
	}

	private DoaPerson(Person personBean) {
		this.personBean = personBean;
	}
	
	public Person getPersonBean() {
		return personBean;
	}

	public void setPersonBean(Person personBean) {
		this.personBean = personBean;
	}
	
	public static DoaPerson getInstance(Person person){
		if(doaPerson == null){
			doaPerson = new DoaPerson(person);
		}
		return doaPerson;
	}
	
	public static DoaPerson getInstance(){
		if(doaPerson == null){
			doaPerson = new DoaPerson();
		}
		return doaPerson;
	}

	

	public void create(Object personBean) {
		Bean2RDF writer = new Bean2RDF(model);
		writer.save((Person)personBean);		
		Writer wr = null;
		try {
			wr = new FileWriter(getPath()+file);
			model.write(wr);
			//System.out.println("written in rdf");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Collection<? extends Object> listAll() {
		Reader r = null;
		try {
			r = new FileReader(getPath()+file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Collection<Person> list = null;
		model = model.read(r, "");
		RDF2Bean reader = new RDF2Bean(model);
		list = reader.load(Person.class);
		return list;
	}

	

	
	

}
